#include <iostream>
#include <unistd.h>
#include <ctime>
#include "BlockQueue.hpp"
#include "Functions.hpp"

using namespace std;

#define P_NUM 1
#define C_NUM 2


void* producer(void* args)
{
    BlockQueue<Task>* bq = (BlockQueue<Task>*)args;
    // int i = 0;
    // while(true)
    // {
    //     bq->push(i++);
    //     cout << "生产了：" << i - 1 << endl;
    //     // sleep(1);
    // }
    while(true)
    {
        int x = rand() % 9 + 1;
        usleep(rand() % 1000); 
        int y = rand() % 9 + 1;
        usleep(rand() % 1000); 
        int type = rand() % 4;
        cout << x << name_v[type] << y << "=?" << endl;
        Task task(x, y, type, func_v[type]);
        bq->push(task);
    }
    return nullptr;
}

void* consumer(void* args)
{
    BlockQueue<Task>* bq = (BlockQueue<Task>*)args;
    // while(true)
    // {
    //     int i;
    //     bq->pop(&i);
    //     cout << "消费了：" << i << endl;
    //     sleep(1);
    // }

    while(true)
    {
        Task task;
        bq->pop(&task);
        cout << task._x << name_v[task._type] << task._y << "=" << task() << endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    lode_func();
    lode_name();
    srand((unsigned long)time(nullptr));
    // 创建线程
    pthread_t p[P_NUM], c[C_NUM];
    BlockQueue<Task>* bq = new BlockQueue<Task>();
    for(int i = 0; i < P_NUM; ++i)
    {
        pthread_create(p + i, nullptr, producer, (void*)bq);
    }
    for(int i = 0; i < C_NUM; ++i)
    {
        pthread_create(c + i, nullptr, consumer, (void*)bq);
    }
    // 阻塞等待，回收线程
    for(int i = 0; i < P_NUM; ++i)
    {
        pthread_join(p[i], nullptr);
    }
    for(int i = 0; i < C_NUM; ++i)
    {
        pthread_join(c[i], nullptr);
    }

    return 0;
}